<template>
  <div class="login">
    <div class="title">湖北省综合运输研究会后台系统</div>
    <el-form class="form" :model="user">
      <el-form-item
        label="账户"
        prop="username"
        :rules="[
          {
            required: true,
            message: '请输入账户',
          },
        ]"
      >
        <el-input v-model="user.username" />
      </el-form-item>
      <el-form-item
        label="密码"
        prop="password"
        :rules="[
          {
            required: true,
            message: '请输入密码',
          },
        ]"
      >
        <el-input type="password" v-model="user.password" />
      </el-form-item>
      <div class="row center">
        <el-button type="primary" @click="login">登录</el-button>
        <el-button @click="register">注册</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import axios from 'axios'
import { useUserStore } from '@/stores/index'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const userStore = useUserStore()
const router = useRouter()

const user = ref({
  username: '',
  password: '',
})

const login = () => {
  axios
    .post('/api/admin/login', {
      hbjtusername: user.value.username,
      hbjtpassword: user.value.password,
    })
    .then((res) => {
      console.log(res)
      // 登录成功，保存token
      if (res.status >= 200 && res.status < 300) {
        userStore.token = res.data.token
        localStorage.setItem('token', userStore.token)

        ElMessage({
          message: '登录成功',
          type: 'success',
        })
        router.replace({
          name: 'article',
        })
      }
    })
    .catch((error) => {
      ElMessage({
        message: '登录失败',
        type: 'error',
      })
    })
}

// 注册
const register = () => {
  router.replace({
    name: 'register',
  })
}
</script>

<style scoped>
.login {
  height: 100vh;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  background-image: linear-gradient(25deg, #006387, #0d8ea4, #0ebbc1, #00ebdf);
}
.title {
  font-size: xx-large;
  margin: 24vh 0 36px 0;
  color: white;
}
.form {
  background: white;
  padding: 48px 48px 24px 48px;
  border-radius: 10px;
}
</style>
